package nccloud.arap.bill.caldisc.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import nc.pub.arap.cons.TradiscCons;
import nc.vo.arap.caltradisc.AggCalDiscVO;
import nc.vo.arap.caltradisc.CalDiscBVO;
import nc.vo.arap.caltradisc.CalDiscVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pubapp.AppContext;
import nccloud.arap.bill.caldisc.bill.util.CommonUtil;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.ui.pattern.billcard.BillCardOperator;

public class CalDiscCALCAction implements ICommonAction {

	@Override
	public Object doAction(IRequest paramIRequest) {
		
		BillCardOperator billCardOperator = new BillCardOperator();
	      // 1、获取AGGVO （request转换主子VO）
		AggCalDiscVO vo = billCardOperator.toBill(paramIRequest);
		
		List<CalDiscBVO> allBodyList = new ArrayList<CalDiscBVO>();
		
		CalDiscBVO[] bodyvos = vo.getBodyVOs();
		
		for(CalDiscBVO bodyvo : bodyvos) {
			if(StringUtils.isNotEmpty(bodyvo.getPrimaryKey())) {
				bodyvo.setStatus(VOStatus.DELETED);
				allBodyList.add(bodyvo);
				
			}
		}
		
		CalDiscVO headvo = vo.getParentVO();
		
		//取到会计期间的值
		String cper = headvo.getCperiod();
		
		if(cper!=null) {
			//计提
			headvo.setCaltime(AppContext.getInstance().getServerTime());
	
			//在商业折扣基础中 组织和会计期间相同的数据 把数据传到表体
			
			//获取商业折扣基础表中的组织和会计期间 交易类型编码
			
			String b_pkorg =  headvo.getPk_org();
			String b_cper =  headvo.getCperiod();
			String b_transtype =  headvo.getTranstype();
			CalDiscBVO[] vos = null;
			if(TradiscCons.BILLTYPE_SYZK_CAL.equals(b_transtype)) {
				try {
					vos = CommonUtil.getFinancingcostMaintainService().queryBasics(vo,TradiscCons.BILLTYPE_SYZK_BAS);
				} catch (BusinessException e) {
					e.printStackTrace();
				}
				if(vos == null) {
					ExceptionUtils.wrapBusinessException("当前应收月份下没有数据或者基础表未维护审批");
				}
					
			}else if(TradiscCons.BILLTYPE_SHFW_CAL.equals(b_transtype)) {
				try {
					vos = CommonUtil.getFinancingcostMaintainService().queryBasics(vo,TradiscCons.BILLTYPE_SHFW_BAS);
				} catch (BusinessException e) {
					e.printStackTrace();
				}
				if(vos == null) {
					ExceptionUtils.wrapBusinessException("当前应收月份下没有数据或者基础表未维护审批");
				}
			}
			
			if(ArrayUtils.isNotEmpty(vos)) {
				
				for(CalDiscBVO temp : vos) {
					temp.setStatus(VOStatus.NEW);
					allBodyList.add(temp);
				}
				
				CalDiscBVO[] allBodys = new CalDiscBVO[allBodyList.size()];
				allBodyList.toArray(allBodys);
				
				vo.setChildrenVO(allBodys);
				Object billcard = billCardOperator.toCard(vo);
			    // 4、返回结果到前端
			    return billcard;
			}
			
			
		}else {
			ExceptionUtils.wrapBusinessException("应收月份不能为空");
		}
		
		
		
		return null;
	}

}
